<template>
    <div>
       <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable  @clear="getUserList" @change="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
                </el-col>
            </el-row>
             <!-- 用户列表数据 -->
            <el-table :data="userList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope = "scope">
                        <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column  label="操作">
                     <template slot-scope="scope">
                         <!-- 修改用户信息按钮 -->
                        <el-button @click="showEditDialog(scope.row.id)" type="primary" icon="el-icon-edit" size='mini'></el-button>
                        <!-- 删除用户按钮 -->
                        <el-button @click="deleteUserById(scope.row.id)" type="danger" icon="el-icon-delete" size='mini'></el-button>
                         <!-- 分配角色 -->
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button @click="setRole(scope.row)" type="warning" icon="el-icon-setting" size='mini'></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
             <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[2, 5, 10, 20]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户对话框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addDialogVisible"
            width="50%"
            @close="addDialogClosed">
                <el-form :model="addForm" status-icon :rules="addFormRules" ref="addFormRef" label-width="70px">
                    <el-form-item label="用户名" prop="username">
                        <el-input  v-model="addForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input  type="password" v-model="addForm.password" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile">
                        <el-input  v-model="addForm.mobile" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input  v-model="addForm.email" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

         <!-- 修改用户信息对话框 -->
         <el-dialog
            title="修改用户"
            :visible.sync="editDialogVisible"
            width="50%"
            @close="editDialogClosed">
                <el-form :model="editForm" status-icon :rules="editFormRules" ref="editFormRef" label-width="70px">
                    <el-form-item label="用户名" >
                        <el-input  v-model="editForm.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile">
                        <el-input  v-model="editForm.mobile"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input  v-model="editForm.email" ></el-input>
                    </el-form-item>
                </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配角色对话框 -->
        <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
            <div>
                <p>当前的用户：{{userInfo.username}}</p>
                <p>当前的角色：{{userInfo.role_name}}</p>
                <p>分配新角色：
                <el-select v-model="selectedRoleId" placeholder="请选择">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
                    </el-option>
                </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
    </el-dialog>

    </div>
</template>

<script>
export default {
    data () {
        // 定义邮箱校验规则
         var checkEmail = (rule, value, callback) => {
             const regEmail = /^\w+@\w+(\.\w+)+$/
             if (regEmail.test(value)) {
                 return callback()
             }
             // 返回错误提示
             callback(new Error('邮箱不正确'))
         }
         var checkMobile = (rule, value, callback) => {
             const regMobile = /^1[3456789]\d{9}$/
             if (regMobile.test(value)) return callback()
             callback(new Error('手机号码不正确'))
         }
        return {
            queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: 5
            },
            userList: [],
            total: 0,
            addDialogVisible: false,
            addForm: {
                username: '',
                password: '',
                mobile: '',
                email: ''
            },
            addFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    // 邮箱验证方法一
                   // { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                   // 邮箱验证方法二
                    { validator: checkEmail, trigger: 'blur' }
                ]
            },
            // 修改用户信息显示与隐藏属性
            editDialogVisible: false,
            editForm: {
                username: '',
                email: '',
                mobile: ''
            },
            editFormRules: {
                 mobile: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ]
            },
            // 用户信息对象
            userInfo: {},
            // 控制分配角色对话框的显示与隐藏
            setRoleDialogVisible: false,
            // 所有角色的数据列表
             roleList: [],
            // 已选中的角色Id值
            selectedRoleId: ''

        }
    },
    created() {
        this.getUserList()
        // 获取sessionStorage中保存的每页显示条数，防止刷新页面是记录消失,获取不到，默认值为5
        this.queryInfo.pagesize = window.sessionStorage.getItem('pagesize') || 5
    },
    methods: {
        async getUserList() {
           const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
           if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
           this.userList = res.data.users
           this.total = res.data.total
        },
        // 每页显示条数改变
        handleSizeChange(newSize) {
           // console.log(newSzie)
            this.queryInfo.pagesize = newSize
            // 将newSize保存到sessionStorage中
            window.sessionStorage.setItem('pagesize', newSize)
            this.getUserList()
        },
        // 页面改变
        handleCurrentChange(newPage) {
            // console.log(newPage)
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        // 更新用户状态
        async changeState (userInfo) {
            // eslint-disable-next-line quotes
            const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state} `)
            if (res.meta.status !== 200) {
                // 更新失败 回滚状态
                userInfo.mg_state = !userInfo.mg_state
                return this.$message.error('状态更新失败')
            }
            this.$message.success('状态更新成功')
        },
        // 关闭添加用户对话框，清空表单中的字段
        addDialogClosed() {
            this.$refs.addFormRef.resetFields()
        },
        // 添加用户
        addUser () {
            // 校验表单
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) return this.$message.error('请填写用户完整信息')
                // 验证通过，请求服务端添加用户
               const { data: res } = await this.$http.post('users', this.addForm)
               if (res.meta.status !== 201) return this.$message.error('添加用户失败')
                this.$message.success('添加用户成功')
                // 将对话框隐藏
                this.addDialogVisible = false
                // 重新获取用户列表
                this.getUserList()
            })
        },

        // 显示修改用户信息表单
        async showEditDialog(id) {
            // 根据id获取用户信息
           const { data: res } = await this.$http.get('users/' + id)
            if (res.meta.status !== 200) return this.$message.error('查询用户信息失败')
            this.editForm = res.data
            this.editDialogVisible = true
        },
        // 监听关闭修改用户信息弹框
        editDialogClosed() {
            this.$refs.editFormRef.resetFields()
        },
        // 修改用户信息
        editUser() {
            // 验证信息
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return this.$message.error('请正确填写用户信息')
                // 发送修改请求
               const { data: res } = await this.$http.put('users/' + this.editForm.id, this.editForm)
               if (res.meta.status !== 200) return this.$message.error('用户信息修改失败')
               // 提示修改成功
               this.$message.success('用户信息修成功')
               // 隐藏弹框
               this.editDialogVisible = false
               // 刷新数据
               this.getUserList()
            })
        },

        // 删除用户
       async deleteUserById (id) {
          const confirmResult = await this.$confirm('请问是否要永久删除该用户, 是否继续?', '删除提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error)
            // 如果用户点击确认，则confirmResult 为'confirm'
            // 如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
            if (confirmResult !== 'confirm') return this.$message.info('已经取消删除')
            const { data: res } = await this.$http.delete('users/' + id)
            // 判断如果删除失败，就做提示
            if (res.meta.status !== 200) return this.$message.error('删除用户失败')
            // 修改成功的提示
            this.$message.success('删除用户成功')
            // 重新请求最新的数据
            this.getUserList()
        },
        // 分配角色
        async setRole (userInfo) {
            this.userInfo = userInfo
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
            this.roleList = res.data
            this.setRoleDialogVisible = true
        },
        // 监听分配角色对话框关闭
        setRoleDialogClosed() {
            this.selectedRoleId = ''
            this.userInfo = ''
        },
        // 保存分配角色
       async saveRoleInfo() {
            if (!this.selectedRoleId) return this.$message.error('请选择要分配的角色！')
            const { data: res } = await this.$http.put(
                `users/${this.userInfo.id}/role`,
                { rid: this.selectedRoleId }
            )
            if (res.meta.status !== 200) return this.$message.error('更新角色失败！')
            this.$message.success('更新角色成功！')
            this.getUserList()
            this.setRoleDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>

</style>